<template>
	<div
		v-on-clickaway="hideDropdown"
		class="v-select"
		:class="[disabled ? 'disabled': '', isShowAccountSelect ? 'v-select-ie': '']"
	>
		<button
			v-if="isShowAccountSelect"
			@click="onToggle"
			type="button"
			:class="[ 'v-select-toggle', show ? 'select-animation-up' : 'select-animation-down' ]"
		>
			<div class="title" :title="title">{{ title }}</div>
			<a-icon class="arrow-down" type="down"/>
		</button>
		<div v-show="show" class="v-dropdown-container" :style="containerStyle">
			<a-input-search
				class="no-shadow"
				:placeholder="$i18n('orgrole.input_keyword')"
				v-model="searchKeyword"
				@change="inputChange"
				@search="onSearch"
			/>
			<a-ztree
				ref="tree"
				class="a-tree-custom-style account-tree-style"
				:checkedKeys="checkedKeys"
				:selected-keys="defaultKeys"
				:expanded-keys="defaultExpandedKeys"
				:tree-data="treeData"
				:showIcon="true"
				:icon="renderIcon"
				:replaceFields="replaceFields"
				@select="onSelect"
				:filterTreeNode="filterNode"
			>
			</a-ztree>
		</div>
	</div>
</template>

<script>
import { mixin as clickaway } from 'vue-clickaway';
import { GroupId } from '@/utils/orgConstants';
import { TreeUtils } from '@/utils/treeUtils';
import seletOrgIconConfig from '../../config/iconfont';

window.selectorInputChangeTimer = null;
export default {
	name: 'accountSelector',
	inject: ['app'],
	mixins: [clickaway],
	components: {},
	props: {
		isShowAccountSelect: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			show: false,
			searchKeyword: '',
			currentItem: {
				title: '请选择',
				id: ''
			},
			replaceFields: {
				title: 'name',
				// children: 'children',
				key: 'id'
			},
			containerStyle: {
				width: '410px',
				height: '270px'
			},
			defaultExpandedKeys: [],
			checkedKeys: []
		};
	},
	computed: {
		title() {
			const { switchAfterUnit, orgSelect } = this.app();
			if (JSON.stringify(switchAfterUnit) !== '{}') {
				return switchAfterUnit.title;
			} else {
				return orgSelect.defaultAccountName;
			}
		},
		treeData() {
			let accountTreeData = this.app().orgSelect.accountTree;
			if (this.app().orgSelect && accountTreeData) {
				let data = TreeUtils.resetTreeData(accountTreeData);
				return data;
			}
			return [];
		},
		disabled() {
			return this.app().orgSelect.onlyLoginAccount;
		},
		defaultKeys() {
			const { switchAfterUnit, orgSelect } = this.app();
			if (switchAfterUnit.id) {
				return [switchAfterUnit.id];
			} else {
				return [orgSelect.defaultAccountId];
			}
		}
	},
	watch: {
		defaultKeys(val) {
			this.onSetExpandDefaultKeys([val]);
		},
		show(val) {
			if (val) {
				this.onSetExpandDefaultKeys(this.defaultKeys);
			}
		}
	},
	methods: {
		hideDropdown() {
			this.doClose();
			this.$emit('toHideDropdown');
		},
		triggerClick(node) {
			if (document.createEvent) {
				var evt = document.createEvent('MouseEvents');
				evt.initEvent('click', true, false);
				node.dispatchEvent(evt);
			} else if (typeof node.onclick == 'function') {
				node.onclick();
			}
		},
		doShow() {
			if (!this.disabled && !this.show) {
				if (this.searchKeyword !== '') {
					this.searchKeyword = '';
					this.$nextTick(()=> {
						this.onSearch('');
					});
				}
				this.show = true;
			}
		},
		doClose() {
			this.show = false;
		},
		onToggle() {
			if (this.show) {
				this.doClose();
			} else {
				this.doShow();
			}
		},
		onSelect(keys, selectData) {
			let node = selectData.node.data;
			if (!node) {
				return;
			}
			const { id: accountId } = this.app().switchAfterUnit;
			if (accountId === node.id) {
				this.$emit('toGetSelectValue', this.currentItem);
				this.hideDropdown();
				return;
			}
			let currentItem = {
				title: node.name,
				id: node.id
			};
			let success = this.app().changeAccount(currentItem);
			if (success) {
				this.currentItem = currentItem;
				this.$emit('toGetSelectValue', this.currentItem);
				this.hideDropdown();
			}
		},
		/**
		 * 设置单位树默认展开的节点
		*/
		onSetExpandDefaultKeys(keys) {
			let key = keys[0];
			if (key) {
				let defaultExpandedKey = key;
				if (key === GroupId && this.treeData[0].children.length) {
					defaultExpandedKey = this.treeData[0].children[0].id;
				}
				let parents = TreeUtils.findParents(this.treeData,defaultExpandedKey);
				if (parents.success) {
					this.defaultExpandedKeys = parents.nodeIds;
					return;
				}
				this.defaultExpandedKeys = [defaultExpandedKey];
			} else {
				// 展开根节点
				this.defaultExpandedKeys = [this.app().orgSelect.accountTree[0].id];
			}
		},
		inputChange(e) {
			if (window.selectorInputChangeTimer !== null) {
				clearTimeout(window.selectorInputChangeTimer);
			}
			let doSearch = this.onSearch.bind(this);
			window.selectorInputChangeTimer = setTimeout(() =>{
				window.selectorInputChangeTimer = null;
				let value = e.target.value;
				doSearch(value);
			},200);
		},
		/**
		 * 树搜索
		*/
		onSearch(value) {
			this.$refs.tree.search(value);
		},
		filterNode(val, data) {
			if (!val) {
				return true;
			}
			return data.name.toLowerCase().indexOf(val.toLowerCase()) !== -1;
		},
		renderIcon() {
			return seletOrgIconConfig.seletOrgIconPath['cap-icon-alternative-company'];
		}
	},
	mounted() {
		let dom = document.getElementById('tabRoot');
		this.containerStyle = {
			width: (dom.clientWidth - 79) / 2 + 'px',
			height: (dom.clientHeight - 2) + 'px'
		};
	}
};
</script>

<style lang="scss" scoped>


* {
	box-sizing: border-box;
}

.fade-enter-active,
.fade-leave-active {
	transition: opacity 0.2s ease;
}

.fade-enter,
.component-fade-leave-to {
	opacity: 0;
}

.v-select {
	// position: relative;
	width: 100%;
	cursor: pointer;
	&.v-select-ie {
		width: 300px;
	}

	&.disabled {
		cursor: not-allowed;
		background: rgba(0, 0, 0, 0.04);

		.v-select-toggle {
			border-color: $borderColor;
			opacity: 0.65;
			cursor: not-allowed;


			&:focus {
				outline: 0 !important;
			}
		}
	}
}

.v-select-toggle {
	display: flex;
	justify-content: space-between;
	height: 32px;
	box-sizing: border-box;
	align-items: center;
	user-select: none;
	padding: 0.375rem 0.75rem;
	color: #333333;
	background-color: transparent;
	width: 100%;
	text-align: right;
	white-space: nowrap;
	font-size: 14px;
	line-height: 1.5;
	transition: background-color, border-color, box-shadow, 0.15s ease-in-out;
	cursor: pointer;
	border: none;

	&:hover {
		border-color: #00a2ff;
	}

	&:focus {
		background-color: white;
		border-color: #00a2ff;
		box-shadow: 2px 2px 2px #eeeeee, -2px -2px 2px #eeeeee;
	}

	.title {
		@include ellipsis();
		display: inline-block;
		flex: 1;
		text-align: left;
		margin-right: 10px;
		color: $defaultFontColor;
	}
}

.select-animation-down {
	.arrow-down {
		transition: all ease 0.3s;
		color: $borderColor;
	}
}

.select-animation-up {
	.arrow-down {
		transition: all ease 0.3s;
		transform: rotate(180deg);
	}
}

.arrow-down {
	display: inline-block;
}

.v-dropdown-container {
	position: absolute;
	left: 15px;
	padding: 0.5rem 0 0 0;
	margin: 0.125rem 0 0;
	text-align: left;
	list-style: none;
	background-color: #fff;
	background-clip: padding-box;
	border-radius: 0.25rem;
	border: 1px solid rgba(0, 0, 0, 0.15);
	z-index: 1009;
	box-shadow: 3px 3px 3px #eeeeee, -3px 3px 3px #eeeeee;

	.current-item {
		background: $hoverColor !important;
		color: $defaultFontColor;
	}
	.tree-node-label {
		color: $defaultFontColor;
	}

	.node-img {
		height: 14px;
		width: 14px;
		margin-right: 7px;
	}
	/*右侧是搜索框*/
	.no-shadow /deep/ .ant-input{
		border-collapse:collapse;
		&:hover,
		&:active,
		&:focus{
			border-color: $borderColor!important;
		}
	}
	.ant-input-search {
		width: calc(100% - 20px);
		margin-left: 10px;
	}

	.a-tree-custom-style {
		height: calc(100% - 32px);
		overflow: auto;
	}
}


/deep/.account-tree-style li span.ant-tree-checkbox-disabled{
	display: none;

}
.account-tree-style{
	padding: 6px 0 0 0;
	box-sizing: border-box;
}

</style>
